import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:package_info/package_info.dart';
import 'package:device_info/device_info.dart';
import 'package:riki_login/api/base_api.dart';
import 'package:riki_login/api/register/register_api.dart';
import 'package:riki_login/api/sms/sms_api.dart';

import '../../riki_login.dart';


///作者：范玉辉
///创建时间：2021/2/8
///说明：注册管家数据管理

class StaffRegisterHouseKeeperViewModel extends SingleViewStateModel {
  late RegisterButlerApi _registerButlerApi;
  late NetEaseSendSmsApi netEaseSendSmsApi; // 发送验证码
  Timer? _timer; //定义变量

  String userPhone = ''; //手机号
  String userCode = ''; // 验证码

  String sendCode = '获取验证码';

  var countdownTime = 0; //倒计时数值

  /// 初始化Api
  void initApi(BuildContext context) {
    _registerButlerApi = RegisterButlerApi(context);
    netEaseSendSmsApi = NetEaseSendSmsApi(context);
  }

  /// 注册工人
  Future<void> registerWorker() async {
    Completer completer = Completer();
    String devicedInfo = await getDeviceInfo();
    String versionInfo = await getVersionInfo();
    _registerButlerApi
        .start(
            params: _registerButlerApi.params(
      userPhone,
      userCode,
      getSendPlatformType(),
      versionInfo,
      devicedInfo,
    ))
        .then((res) {
      if (res.success ?? false) {
        ToastUtil.showPositiveToast('恭喜您，注册成功~');
        // Provider.of<UserViewModel>(context!, listen: false).userLogin(res.result!);
        //替换为上面的方法
        // Global.saveUserAccount(res.result);
        RikiLogin.instance.refreshStaffLoginEntity(res.result!);
        RikiBase.setAccessToken(res.result!.accessToken!);
      } else {
        ToastUtil.showNegativeToast(res.message);
      }
      completer.complete();
    });
    return completer.future;
  }

  /// 60秒倒计时
  void startCountdown() {
    countdownTime = 60;
    sendCode = '($countdownTime)秒重发';
    notifyListeners(refreshVM: false);
    final call = (timer) {
      if (countdownTime == 0) {
        _timer?.cancel();
        _timer = null;
        sendCode = '重发';
      } else {
        sendCode = '($countdownTime)秒重发';
      }
      countdownTime -= 1;
      notifyListeners(refreshVM: false);
    };
    _timer = Timer.periodic(Duration(seconds: 1), call);
  }

  @override
  void dispose() {
    super.dispose();
    netEaseSendSmsApi.cancel();
    _registerButlerApi.cancel();

    _timer?.cancel();
    _timer = null;
  }

  //获取设备信息
  Future<String> getDeviceInfo() async {
    DeviceInfoPlugin deviceInfo = new DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      return androidInfo.id;
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      return iosInfo.identifierForVendor;
    }
    return '';
  }

  //获取哪个平台
  String getSendPlatformType() {
    return Platform.isAndroid ? '2' : '1';
  }

  //获取版本号
  Future<String> getVersionInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }

  /// 发送验证码
  Future<void> sendSmsCodeFun(String neCaptchaValidate) {
    Completer completer = Completer();
    netEaseSendSmsApi.start(params: netEaseSendSmsApi.params(userPhone.trim().toString(), neCaptchaValidate, 3)).then((res) {
      if (res.success ?? false) {
        ToastUtil.showPositiveToast('验证码已发送，请注意查收!');
        startCountdown();
      } else {
        ToastUtil.showNegativeToast(res.message);
      }
      completer.complete();
    });
    return completer.future;
  }

  @override
  Future loadData() {
    throw UnimplementedError();
  }

  @override
  onCompleted(data) {
    throw UnimplementedError();
  }
}
